﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Payroll.BusinessLogic;
using Payroll.Common.Utils;
using Payroll.Common.Utils.Html;
using PayrollHR.Web;
using Payroll.BusinessLogic.CustomerManager;
using Payroll.BusinessLogic.Directory;
using Payroll.BusinessLogic.Utils;
using Payroll.BusinessLogic.ExportImport;
using MigraDoc.DocumentObjectModel;
using Payroll.BusinessLogic.Package;
using System.IO;
using OfficeOpenXml;
using OfficeOpenXml.DataValidation;

namespace PayrollHR.Administration.Modules
{
    public partial class ListPackage : BasePayrollAdministrationUserControl
    {
        private const int m_pageSize = 50;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.BindGrid();
            }
        }
        protected void BindGrid()
        {
            var pack = GetPackages();
            gvCustomers.DataSource = pack;
            gvCustomers.DataBind();
        }
        protected List<Package> GetPackages()
        {
            var pack = PackageSearch1.GetPackage();
            List<Package> package = PackageService.GetAllPackage(pack, m_pageSize);
            return package;
        }
        protected void LoadGrid()
        {
            var pack = LoadPackage();
            gvCustomers.DataSource = pack;
            gvCustomers.DataBind();
        }
        protected List<Package> LoadPackage()
        {
            int Useid = PayrollContext.Current.Session.EmployeeId;
            PackageSearch packCollection = new PackageSearch
            {
                UserId= Useid,
                PackName="",
                PackDate=0,
                PackId=0
            };
            List<Package> pack = PackageService.GetAllPackage(packCollection, m_pageSize);
            return pack;
        }
        protected void gvCustomers_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvCustomers.PageIndex = e.NewPageIndex;
            BindGrid();
        }
   
        protected void SearchButton_Click(object sender, EventArgs e)
        {
            this.BindGrid();
        }
        protected void btnExportXLS_Click(object sender, EventArgs e)
        {

        }
        protected void btnToPdf_Click(object sender, EventArgs e)
        {

        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    List<int> packCollection = new List<int>();
                    foreach (GridViewRow row in gvCustomers.Rows)
                    {
                        CheckBox cbCustomerInfo = row.FindControl("cbCustomerInfo") as CheckBox;
                        HiddenField hfCustomerID = row.FindControl("hfCustomerID") as HiddenField;
                        int CustomerID = int.Parse(hfCustomerID.Value);
                        if (cbCustomerInfo.Checked)
                        {
                            packCollection.Add(CustomerID);
                        }
                    }
                    if (packCollection.Count > 0)
                    {
                        PackageService.Delete(packCollection);
                        this.BindGrid();
                    }
                }
                catch (Exception exc)
                {
                    ProcessException(exc);
                }
            }
        }
        protected void gvCustomers_RowDataBound(object sender, GridViewRowEventArgs e)
        {
        }
        protected void gvCustomers_RowCommand(object sender, GridViewCommandEventArgs e)
        {

        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            string fileName = string.Format("Mau_DE_NGHI_CAP_CKS_CKCA_{0}", DateTime.Now.ToString("dd-MM-yyyy_HH.mm") + ".xlsx");

           // string fileName = string.Format("CustomerList_{0}_{1}.xlsx", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"), CommonHelper.GenerateRandomDigitCode(4));
            FileInfo newFile = new FileInfo(Server.MapPath(@"..\Administration\FileExport\" + fileName));// string filePath = string.Format("{0}Administration\\FileExport\\{1}", HttpContext.Current.Request.PhysicalApplicationPath, fileName);
            FileInfo template = new FileInfo(Server.MapPath(@"..\Files\Template\CKCA New.xlsx"));
            var listPack = GetPackages();
            int maxResult = listPack.Count;
            writeSheets(newFile, template, maxResult, listPack);
          //  ExcelHelper.ExportCustomerToExcel(customer, ref filePath, fileTeamplate);
            hlexport.Visible = true;
            hlexport.Text = "Save As File Export";
            hlexport.NavigateUrl = "../FileExport/" + fileName;    
        }
        private void writeSheets(FileInfo newFile, FileInfo template, int maxRow, List<Package> pack)
        {
            int index = 0;
            int rowIndexCurrentRecord = 5;
            using (var xlPackage = new ExcelPackage(newFile, template))
            {
                ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets[1];
                
                while (index < maxRow)
                {
                   // worksheet.Row(rowIndexCurrentRecord).Height = 20;
                    worksheet.Cells["A" + rowIndexCurrentRecord].Value = index + 1;// stt.ToString();
                  //  worksheet.Cells["I" + rowIndexCurrentRecord].Value = pack[index].PackCode.ToString();
                    string add = "I" + rowIndexCurrentRecord.ToString();
                    var validation = worksheet.DataValidations.AddListValidation(add);
                    validation.ShowErrorMessage = true;
                    foreach (var item in pack)
                    {
                        validation.Formula.Values.Add(item.PackCode.ToString());
                    }
                    rowIndexCurrentRecord++;
                    index++;
                }
                xlPackage.Save();
            }
        }
    }

}